package com.bigdata.controller;/**
 * Created by Administrator on 2019/7/5 0005.
 */

import com.bigdata.utils.FreeMarkerUtil;
import com.bigdata.utils.GetBasePath;
import com.bigdata.utils.ResponseUtil;
import com.bigdata.utils.ServletUtils;
import freemarker.template.TemplateException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Administrator
 * @description
 * @date 2019/7/5 0005
 */
@Controller
public class NotFoundController implements ErrorController {

    Logger logger = LoggerFactory.getLogger("");

    @Override
    public String getErrorPath() {
        return "/error";
    }

    @RequestMapping("/error")
    @ResponseBody
    public Object error(HttpServletRequest request, HttpServletResponse response) {
        if (ServletUtils.isAjaxRequest(request)) {
            Map<String, Object> body = new HashMap<String, Object>();
            body.put("error", "页面没有找到！");
            body.put("code", "404");
            return body;
        } else {
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("basePath", request.getContextPath());
            String html = "";
            try {
                html = FreeMarkerUtil.toStringTem(GetBasePath.getWebPath() + "templates/error/", "404.html", data);
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
                html = "<html><body>页面不存在！</body></html>";
            }
            ResponseUtil.renderText(response, html);
        }
        return null;
    }
}
